package com.xhs.hawaii.framework;

import com.xhs.hawaii.common.SsoService;
import com.xhs.hawaii.common.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tangchuang
 * @version 1.0
 * @since 2018/1/25
 */
@Slf4j
public class AuthenticationFilter extends GenericFilterBean {

    private SsoService ssoService;

    public AuthenticationFilter(SsoService ssoService) {
        this.ssoService = ssoService;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        byte[] noLogin = "请登陆".getBytes("UTF-8");

        String token = httpRequest.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            httpResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
            httpResponse.getOutputStream().write(noLogin);
            return;
        }
        UserInfo userInfo = null;
        if (StringUtils.isNotBlank(token)) {
            try {
                userInfo = ssoService.getUserInfo(token);
            } catch (Exception e) {
                log.error("获取登陆信息异常", e);
                httpResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
                httpResponse.getOutputStream().write("请登录".getBytes("UTF-8"));
                return;
            }
        }
        if (userInfo == null) {
            httpResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
            httpResponse.getOutputStream().write(noLogin);
            return;
        }
        UserInfoBag.cleanAndSet(userInfo);
        try {
            MDC.put("token", token);
            chain.doFilter(request, response);
        } finally {
            MDC.remove("token");
            UserInfoBag.clean();
        }
    }
}
